<template>
  <div class="relative size-full flex items-center justify-center overflow-hidden" :style="{ backgroundColor: bgColor }">
    <WaveBg :theme-color="bgThemeColor" />
    <div class="relative z-4 w-auto rd-12px">
      <div class="w-[430px] lt-sm:w-300px login-main">
        <header class="flex items-center justify-between">
          <SvgIcon icon-class="logo" class="text-64px lt-sm:text-48px" />
          <h3 class="text-28px c-[#646cff] font-500 lt-sm:text-22px">鸿鹄数科管理系统</h3>
          <div class="i-flex-col">
            <!-- <LangSwitch v-if="themeStore.header.multilingual.visible" :lang="appStore.locale"
							:lang-options="appStore.localeOptions" :show-tooltip="false" @change-lang="appStore.changeLocale" /> -->
          </div>
        </header>
        <main>
          <div class="pt-24px">
            <ElForm ref="loginRef" :show-label="false" :model="loginForm" :rules="loginRules">
              <ElFormItem prop="username">
                <ElInput size="large" v-model="loginForm.username" placeholder="请输入用户名" />
              </ElFormItem>
              <ElFormItem prop="password">
                <ElInput size="large" v-model="loginForm.password" auto-complete="off" type="password" placeholder="请输入密码" />
              </ElFormItem>
              <ElFormItem v-if="captchaEnabled" prop="code">
                <ElInput v-model="loginForm.code" size="large" auto-complete="off" style="width: 67%" @keyup.enter="handleLogin" placeholder="验证码">
                  <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
                </ElInput>
                <div class="login-code">
                  <img :src="codeUrl" class="login-code-img" @click="getCode" />
                </div>
              </ElFormItem>
              <ElSpace direction="vertical" :size="24" class="w-full" fill>
                <div class="flex-y-center justify-between">
                  <ElCheckbox v-model="loginForm.rememberMe">记住密码</ElCheckbox>
                </div>
                <ElButton size="large" type="primary" round @click.prevent="handleLogin" :loading="loading">
                  <span v-if="!loading">{{ proxy.$t('login.login') }}</span>
                  <span v-else>{{ proxy.$t('login.logging') }}</span>
                </ElButton>
                <ElDivider class="text-14px text-#666 !m-0">其他账号登录</ElDivider>
                <div class="flex items-center justify-center gap-12px">
                  <img style="width: 30px" src="@/assets/images/dingtalk.png" alt="" />
                  <img style="width: 30px" src="@/assets/images/wchat.png" alt="" />
                </div>
              </ElSpace>
            </ElForm>
          </div>
        </main>
      </div>
    </div>
  </div>
</template>
<script setup>
import WaveBg from '@/views/login/modules/wave-bg.vue';
import { mixColor } from '@/color/index';
import { getCodeImg, getTenantList } from '@/api/login';
import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import { to } from 'await-to-js';
import HttpStatus from '@/enum/RespEnum';
import { useI18n } from 'vue-i18n';
const bgColor = computed(() => {
  const COLOR_WHITE = '#ffffff';
  const ratio = 0.2;
  const color = '#646cff';
  return mixColor(COLOR_WHITE, color, ratio);
});
const bgThemeColor = '#646cff';
const { proxy } = getCurrentInstance();
const title = import.meta.env.VITE_APP_TITLE;
const userStore = useUserStore();
const router = useRouter();
const { t } = useI18n();
const loginForm = ref({
  tenantId: '000000',
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: ''
});
const loginRules = {
  tenantId: [{ required: true, trigger: 'blur', message: t('login.rule.tenantId.required') }],
  username: [{ required: true, trigger: 'blur', message: t('login.rule.username.required') }],
  password: [{ required: true, trigger: 'blur', message: t('login.rule.password.required') }],
  code: [{ required: true, trigger: 'change', message: t('login.rule.code.required') }]
};

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(true);

// 注册开关
const register = ref(false);
const redirect = ref('/');
const loginRef = ref();
// 租户列表
const tenantList = ref([]);
watch(
  () => router.currentRoute.value,
  (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect && decodeURIComponent(newRoute.query.redirect);
  },
  { immediate: true }
);
const handleLogin = () => {
  loginRef.value?.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', String(loginForm.value.tenantId));
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        // 否则移除
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      // 调用action的登录方法
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        const redirectUrl = redirect.value || '/';
        await router.push(redirectUrl);
        loading.value = false;
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};
const getLoginData = () => {
  const tenantId = localStorage.getItem('tenantId');
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe)
  };
};

/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList(false);
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type) => {
  authBinding(type, loginForm.value.tenantId).then((res) => {
    if (res.code === HttpStatus.SUCCESS) {
      // 获取授权地址跳转
      window.location.href = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};
onMounted(() => {
  getCode();
  initTenantList();
  getLoginData();
});
</script>
<style lang="scss" scoped>
.login-main {
  border: 1px solid #dee0e5;
  border-radius: 10px;
  background-color: #ffffff;
  padding: 10px;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}

:deep(.el-input__wrapper) {
  height: 40px !important;
}
</style>
